require(['./config'], () => {
    require(['template', 'login-reg', 'server', 'nav', 'foot'], (template, loginreg, server, nav) => {
        class Shoplist {
            constructor() {
                this.init()
            }
            bindEvent() {
                const _this = this
                let phone = this.phone;
                $('tr .drop').on('click', function() {
                    let res = confirm("确定删除此条购物车吗？")
                    let goods_id = $(this).parents('tr').attr('data-id')
                    if (res && phone) {
                        $.post(server.baseServerUrl + '/api/goodscart/delcart', { _id: goods_id, phone }, resp => {
                            $(this).parents('tr').remove();
                            _this.cart = _this.cart.filter((item) => {
                                return item._id != goods_id
                            })
                            _this.checksChange()
                            _this.setAllcheckStatus()
                            _this.calcTotalMoney()
                        })
                    }
                })
                $('tr .pointer.reduce-count').on('click', function() {
                    let goods_count = $(this).parents('tr').find('.numss').val();
                    let goods_id = $(this).parents('tr').attr('data-id')
                    if (goods_count <= 1) {
                        return
                    }
                    goods_count = goods_count - 1;

                    $(this).parents('tr').find('.numss').val(goods_count)
                    if (phone) {
                        $.post(server.baseServerUrl + '/api/goodscart/updatecarcount', { _id: goods_id, phone, goods_count }, resp => {
                            // console.log(resp);
                            _this.cart.forEach((item) => {
                                if (item._id == goods_id) {
                                    item.count--
                                }
                            })
                            _this.calcTotalMoney()
                        })
                    } else {
                        _this.cart.forEach((item) => {
                            if (item._id == goods_id) {
                                item.count--
                            }
                        })

                        localStorage.setItem('cart', JSON.stringify(_this.cart))
                        _this.calcTotalMoney()
                    }

                })
                $('tr .pointer.add-count').on('click', function() {
                    let goods_count = $(this).parents('tr').find('.numss').val();
                    goods_count = goods_count * 1 + 1;
                    let goods_id = $(this).parents('tr').attr('data-id');
                    $(this).parents('tr').find('.numss').val(goods_count)
                    if (phone) {
                        $.post(server.baseServerUrl + '/api/goodscart/updatecarcount', { _id: goods_id, phone, goods_count }, resp => {
                            // console.log(resp);
                            _this.cart.forEach((item) => {
                                if (item._id == goods_id) {
                                    item.count++
                                }
                            })
                            _this.calcTotalMoney()
                        })
                    } else {
                        _this.cart.forEach((item) => {
                            if (item._id == goods_id) {
                                item.count++
                            }
                        })
                        localStorage.setItem('cart', JSON.stringify(_this.cart))
                        _this.calcTotalMoney()
                    }
                })
            }
            init() {
                $.get(server.baseServerUrl + '/user/isLogin', resp => {
                    if (resp.code === 200) {
                        let phone = resp.body.phone
                        this.phone = phone
                        this.loginRender(phone)
                    } else {
                        this.noLoginRender();
                    }
                })
            }
            noLoginRender() {
                let cart = localStorage.getItem('cart')

                if (cart) {
                    this.cart = JSON.parse(cart)
                    console.log(this.cart);

                    $('.table_tb').show()

                    $('.no_goods').hide()
                    this.render()
                    this.checksChange()
                    this.calcTotalMoney()
                    this.setAllcheckStatus()
                    this.bindEvent()
                } else {
                    $('.table_tb').hide()
                    $('.no_goods').show()

                }
            }
            render() {
                $('#shopcart-list').html(template('shopcart-list-template', { list: this.cart }))
            }
            checksChange() {
                const _this = this
                let phone = this.phone;

                $('#shopcart-list .checks').on('change', function() {
                    // 从当前input出发，在tr身上拿到当前商品的id
                    const id = $(this).parents('tr').attr('data-id')

                    // 根据id修改当前商品的check属性
                    _this.cart = _this.cart.map(shop => {
                            if (shop._id == id) {
                                shop.check = $(this).prop('checked')
                            }
                            return shop
                        })
                        // 把_this.cart修改之后的数据重新存localStorage

                    if (!phone) {
                        localStorage.setItem('cart', JSON.stringify(_this.cart))
                    }
                    // 把数据修改了以后重新调用一下计算总价的方法就行了
                    _this.calcTotalMoney()
                        // 每一次单选切换了状态都要判断全选然后设置状态
                    _this.setAllcheckStatus()
                })
                $('#all-check').on('change', function() {

                    _this.cart.forEach(shop => { shop.check = $(this).prop('checked') })
                    if (!phone) {
                        localStorage.setItem('cart', JSON.stringify(_this.cart))
                    }
                    _this.render()
                    _this.checksChange()
                    _this.calcTotalMoney()
                    _this.setAllcheckStatus()
                    _this.bindEvent()
                })
            }

            setAllcheckStatus() {
                $('#all-check').prop('checked', this.cart.every(shop => shop.check))

            }
            calcTotalMoney() {
                // 不管如何修改，都根据数据从头算

                const money = this.cart.reduce((sum, shop) => {
                    if (shop.check) {
                        sum += shop.price * shop.count
                    }
                    return sum
                }, 0)
                $('#allPay').html(money)
            }
            loginRender(phone) {
                let cart = localStorage.getItem('cart')

                if (cart) {
                    cart = JSON.parse(cart)
                    cart.forEach((item) => {
                        let goods_id = item._id;
                        let goods_count = item.count;
                        let car_size = item.car_size;
                        $.post(server.baseServerUrl + '/api/goodscart/addcart', { _id: goods_id, phone, goods_count, car_size }, resp => {
                            console.log(resp);
                        })
                    })
                } else {
                    cart = []
                }

                $.post(server.baseServerUrl + '/api/goodscart/selectcart', { phone }, resp => {
                    if (resp.code != 200) {
                        $('.no_goods').show().removeClass('hidden');
                    } else {
                        let shopcar_list = resp.body.list
                        let goods_list = [];
                        this.allPay = 0;
                        let promise = new Promise((resolve) => {
                            shopcar_list.forEach((item) => {
                                let goodid = item._id;
                                $.post(server.baseServerUrl + '/api/goods/selectOne', { _id: goodid }, resp => {
                                    if (resp.code != 200) {
                                        return
                                    }
                                    let res = resp.body.list
                                    res.img = res.img.split('@')
                                    res.car_size = item.car_size
                                    res.count = item.goods_count
                                    res.check = cart.some((item) => {
                                        return item.goodid == goodid
                                    });
                                    res.total_item = item.goods_count * res.price
                                    this.allPay += res.total_item;
                                    goods_list.push(res)

                                    if (goods_list.length == shopcar_list.length) {
                                        resolve()
                                    }
                                })
                            })
                        })
                        promise.then(() => {
                            $('.table_tb').show().removeClass('hidden');
                            $('.no_goods').hide().addClass('hidden');
                            const str = template('shopcart-list-template', {
                                list: goods_list
                            })
                            $('#shopcart-list').html(str)
                            this.cart = goods_list

                            this.checksChange()
                            this.calcTotalMoney()
                            this.setAllcheckStatus()
                            this.bindEvent()
                            localStorage.removeItem('cart');
                        })
                    }
                })

            }
        }
        new Shoplist()
    })
})